package ru.cjay.loading {
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.utils.Dictionary;

public class ResourceManager {

    private static var _instance:ResourceManager;
    private static var allowInstantiation:Boolean=false;

    private var names:Dictionary;
    private var resources:Dictionary;
    private var swf_asset:Dictionary;

    public static function getInstance():ResourceManager
    {
        if (!_instance)
        {
            allowInstantiation = true;
            _instance = new ResourceManager();
            allowInstantiation = false;
        }
        return _instance;
    }

    public function addNameToURL(url:String, name:String):void
    {
        if (url in resources)
        {
            names[name]=url;
        }
    }

    public function addResource(url:String, object:DisplayObject, name:String=null):void{
        resources[url] = object;
        if (name)
        {
            names[name]= url;
        }
    }

    public function addSwfAsset(name:String, object:Class):void{
        swf_asset[name]=object;
    }

    public function getSwfAssetClass(name:String):Class{
        return swf_asset[name];
    }



    public function getResourceByName(name:String):DisplayObject{
        if (!(name in names)) return null;
        var url:String = names[name];
        if (!(url in resources)) return null;

        return resources[url] as DisplayObject;
    }

    /*
    Возвращает ресурс по url
     */


    public function getResource(url:String):DisplayObject{
        if (url in resources){
            return resources[url] as DisplayObject;
        }
        return null;
    }


    public function hasResource(url:String):Boolean
    {
        return url in resources;
    }

    public function ResourceManager():void {
          if (!allowInstantiation){
              throw new Error("Error: Instantiation failed: Use ResourceManager.getInstance() instead of new.");
       }
        names = new Dictionary();
        resources = new Dictionary();
        swf_asset = new Dictionary();
    }
}
}
